<?php
use App\Helpers\Bing;
use App\Models\Picture;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

if (! function_exists('rsp')) {
    /**
     * 格式化API返回内容
     * @param null $data
     * @param int $code
     * @param null $message
     * @return array
     */
    function rsp($data = null, $code = 20000, $message = null)
    {
        $errors = [
            '20000' => '成功',
            '20001' => '参数错误',
            '40000' => '资源不存在',
            '40003' => '系统内部错误，请联系管理员',
            '40004' => '今天的壁纸尚未更新，请稍后重试',
        ];
        return [
            'code' => $code,
            'data' => $data,
            'message' => $message ? $message : $errors[$code],
        ];
    }
}

if (! function_exists('debugger')) {
    /**
     * 自定义的日志输出函数
     * @param $content
     * @param null $filename
     * @param null $line
     */
    function debugger($content, $filename = null, $line = null)
    {
        logger('********************************** START ******************************************');
        logger('当前文件为：' . $filename);
        logger('当前代码执行位置为：' . $line);
        logger('****** 详细日志内容如下： ******');
        logger($content);
        logger('********************************** END ******************************************');
    }
}

if (! function_exists('download')) {
    /**
     * 壁纸保存本地
     * @return array
     */
    function download()
    {
        debugger('必应壁纸下载', __FILE__, __LINE__);
        $b = new Bing();
        $items = $b->getLatestPic();
        foreach ($items as $item) {
            $date = $item['enddate'];
            $date = substr_replace($date, '-', 6, 0);
            $date = substr_replace($date, '-', 4, 0);
            $cp = $item['copyright'];
            $cp = str_replace(')', '', $cp);
            $cp = explode('(', $cp);
            $title = $cp[0];
            $copyright = $cp[1];
            $bing = Picture::where('hsh', $item['hsh'])->where('datetime', $date)->first();
            if (empty($bing)) {
                // 下载图片回本地
                $url = $item['url'];
                $path = $b->download($url);
                list($width, $height, $type, $attr) = getimagesize(
                    base_path() . '/storage/app' . $path
                );
                $bing = new Picture();
                $bing['title'] = $title;
                $bing['copyright'] = $copyright;
                $bing['url'] = $url;
                $bing['path'] = str_replace('public', 'storage', $path);
                $bing['filename'] = str_replace(
                    '/th?id=',
                    '',
                    $item['urlbase']
                );
                $bing['resolution'] = $width . 'x' . $height;
                $bing['datetime'] = $date;
                $bing['hsh'] = $item['hsh'];
                $bing->save();
            }
        }
        debugger($bing, __FILE__, __LINE__);
        return $items;
    }
}
